﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
using System.Diagnostics;

namespace AbstractLabs.PowerShell.Yammer
{
	[Cmdlet(VerbsCommon.Set, "Yammer-Authorization")]
	public class AuthorizationCmdlet : Cmdlet
	{
		protected override void BeginProcessing()
		{
			base.BeginProcessing();
			try
			{
					
				OAuthConsumerContext context = new OAuthConsumerContext();
				context.ConsumerKey = Properties.Settings.Default.ConsumerKey;
				context.ConsumerSecret = Properties.Settings.Default.ConsumerSecret;
				context.SignatureMethod = SignatureMethod.HmacSha1;
				OAuthSession session = new OAuthSession(context,Properties.Settings.Default.RequestUrl, Properties.Settings.Default.AuthorizeUrl, Properties.Settings.Default.AccessUrl);
				IToken token = session.GetRequestToken();
				string authorizationLink = session.GetUserAuthorizationUrlForToken(token);
				Process.Start(authorizationLink);
				Console.WriteLine(String.Format("Pin Access Url:{0}", authorizationLink));
				Console.Write("Enter Pin:");
				string pin = Console.ReadLine();
				Properties.Settings.Default.Token = (TokenBase)session.ExchangeRequestTokenForAccessToken(token, pin);
				Properties.Settings.Default.Save();
				Console.WriteLine("Access token has been set successfully");
			}
			catch (Exception exception)
			{
				ThrowTerminatingError(new ErrorRecord(exception, String.Empty, ErrorCategory.WriteError, null));
			}
		}

	}
}
